wx.cloud.init()
const db = wx.cloud.database()
const teacherCollection = db.collection('teacher')
const _ = db.command
const genCloudFilePath = function (localFilePath) {
  console.log("localFilePath" + localFilePath)
  const suffix = localFilePath.substring(localFilePath.length, localFilePath.lastIndexOf(".")) || '.jpg';//后缀名
  const now = new Date()
  const year = now.getFullYear();
  let month = now.getMonth() + 1;
  let day = now.getDate();
  let hour = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;
  hour = hour < 10 ? '0' + hour : hour;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  seconds = seconds < 10 ? '0' + seconds : seconds;
  const yyyyMMddHHmmss = `${year}${month}${day}${hour}${minutes}${seconds}`;
  return 'upload/' + year + month + '/' + yyyyMMddHHmmss + Math.random().toString(10).substr(2, 10) + suffix;
};
Component({
  data: {
    showTopTips: false,
    detailList: [],
    formData: {
    },
    id: "",
    courses: ['语文', '数学', '英语', '历史', '地理', '政治', '化学', '物理', '生物'],
    courseIndex: 0,
    rules: [{
      name: 'name',
      rules: { required: true, message: '姓名是必选项' },
    }, {
      name: 'no',
      rules: { required: true, message: '编号是必选项' },
    }, {
      name: 'sex',
      rules: [{ required: true, message: '性别必填' }],
    }, {
      name: 'year',
      rules: { required: true, message: '教龄是必选项' },
    }, {
      name: 'grade',
      rules: { required: true, message: '可辅导年级是必选项' },
    }, {
      name: 'score',
      rules: { required: true, message: '过往辅导成绩是必选项' },
    }, {
      name: 'cost',
      rules: { required: true, message: '课时费是必选项' },
    },{
      name:'area',
      rules:{required:true,message:'所在地区必选项'}
    }]
  },
  methods: {
    onLoad: function (options) {
      console.log(options.id)
      teacherCollection.doc(options.id).get({
        success: res => {
          console.log(res.data)
          var course = res.data.course;
          var index = 0;
          if (course == '语文') {
            index = 0;
          }
          if (course == '数学') {
            index = 1;
          }
          if (course == '英语') {
            index = 2;
          }
          if (course == '历史') {
            index = 3;
          }
          if (course == '地理') {
            index = 4;
          }
          if (course == '政治') {
            index = 5;
          }
          if (course == '化学') {
            index = 6;
          }
          if (course == '物理') {
            index = 7;
          }
          if (course == '生物') {
            index = 8;
          }
          this.setData({
            teacher: res.data,
            courseIndex: index,
            formData:res.data,
            detailList: res.data.detail!=undefined?res.data.detail:[],
            id: res.data._id,
          })
        }
      })
    },
    formInputChange(e) {
      const { field } = e.currentTarget.dataset
      this.setData({
        [`formData.${field}`]: e.detail.value
      })
    },
    bindCourseChange: function (e) {
      console.log('picker country 发生选择改变，携带值为', e.detail.value);

      this.setData({
        courseIndex: e.detail.value
      })
    },
    submitForm() {
      var that = this;
      this.selectComponent('#form').validate((valid, errors) => {
        console.log('valid', valid, errors)
        if (!valid) {
          const firstError = Object.keys(errors)
          if (firstError.length) {
            this.setData({
              error: errors[firstError[0]].message
            })

          }
        } else {
          var index = this.data.teacher._id
          console.log(index)
          var index = this.data.courseIndex
          var course = that.data.courses[index]
          console.log(this.data.detailList)
          wx.cloud.callFunction({
            name: 'updateTeacher',
            data: {
              id: this.data.teacher._id,
              name: this.data.formData.name,
              no: this.data.formData.no,
              course: course,
              sex: this.data.formData.sex,
              year: this.data.formData.year,
              grade: this.data.formData.grade,
              score: this.data.formData.score,
              cost: this.data.formData.cost,
              detail: this.data.detailList,
              area:this.data.formData.area
            }
          }).then(res => {
            wx.showToast({
              title: '更新成功',
              icon: 'success',
              duration: 2000
            })
            wx.redirectTo({
              url: '../teachermanage/teachermanage',
            })
          }).catch(err => {
            // handle error
          })
          /*teacherCollection.add({
            // data 字段表示需新增的 JSON 数据
            data: {
              name: this.data.formData.name,
              no: this.data.formData.no,
              course: course,
              sex: this.data.formData.sex,
              year: this.data.formData.year,
              grade: this.data.formData.grade,
              score: this.data.formData.score,
              cost: this.data.formData.cost,
              createtime: new Date()
            }
          })
            .then(res => {
              console.log(res)
              wx.showToast({
                title: '增加成功',
                icon: 'success',
                duration: 2000
              })
              wx.redirectTo({
                url: '../teachermanage/teachermanage',
              })
            })
            .catch(console.error)*/
        }
      })
    },
    DelDetail(e) {
      wx.showModal({
        title: '操作确认',
        content: '确定要删除这张照片吗？',
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            let id = e.currentTarget.dataset.id;
            if (id.indexOf("cloud") != -1) {
              wx.cloud.deleteFile({
                fileList: [id]
              }).then(res => {
                // handle success
                console.log(res.fileList)
              }).catch(error => {
                // handle error
              })
            }
            this.data.detailList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
              detailList: this.data.detailList
            })
          }
        }
      })
    },
    uploadImg(filePath) { // 调用wx.cloud.uploadFile上传文件
      return wx.cloud.uploadFile({
        cloudPath: genCloudFilePath(filePath),
        filePath: filePath
      })
    },
    ViewDetail(e) {
      wx.previewImage({
        urls: this.data.detailList,
        current: e.currentTarget.dataset.url
      });
    },
    ChooseDetail() {
      var that = this;
      console.log(this.data.detailList)
      wx.chooseImage({
        count: 9, //默认9
        sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: (res) => {
          const uploadTasks = res.tempFiles.map(item => this.uploadImg(item.path))
          Promise.all(uploadTasks).then(result => {
            const uploaddetailList = result.map(img => (img.fileID));
            console.log(that.data.detailList)
            if (this.data.detailList.length != 0) {
              this.setData({
                detailList: this.data.detailList.concat(uploaddetailList)
              })
            } else {
              this.setData({
                detailList: uploaddetailList
              })
            }
            teacherCollection.doc(this.data.id).update({
              data: {
                detail: this.data.detailList
              }
            })
          })
        }
      });
    },
  }
});